<template>
  <div>
    <el-form :inline="true" :model="searchGood" class="demo-form-inline">
      <el-form-item label="商品名称">
        <el-input
            size="mini"
            v-model="searchGood.goodName"
            placeholder="请输入商品名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="商品描述">
        <el-input
            size="mini"
            v-model="searchGood.goodDes"
            placeholder="请输入商品描述"
        ></el-input>
      </el-form-item>


      <el-form-item label="商品品牌">
        <el-select size="mini" v-model="searchGood.brdCode" placeholder="请选择" value-key="id">
          <el-option
              v-for="item in brandList"
              :key="item.value"
              :label="item.brdName"
              :value="item.brdCode"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="商品类别">
        <el-select size="mini" v-model="searchGood.typeCode" placeholder="请选择" value-key="id">
          <el-option
              v-for="item in goodTypeList"
              :key="item.value"
              :label="item.typeName"
              :value="item.typeCode"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="商品供应商">
        <el-select size="mini" v-model="searchGood.supCode" placeholder="请选择" value-key="id">
          <el-option
              v-for="item in supplierList"
              :key="item.value"
              :label="item.supName"
              :value="item.supCode"
          />
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button size="small" type="primary" @click="page()">查询</el-button>
        <el-button size="small" type="info" @click="clearInfo2();page()">清空</el-button>
      </el-form-item>


      <el-button icon="el-icon-shopping-cart-2" type="primary" @click="sealsShowVi=true" style="float: right">购物车
      </el-button>
    </el-form>


    <!-- 数据表格 -->
    <template>
      <div>
        <el-row>
          <el-col :span="6" v-for="(it, index) in tableData" :key="it.goodCode">
            <el-card :body-style="{ padding: '0px'}" style="margin: 8px" @click.native="handleCardClick(it)">
              <img :src="it.goodImg" class="image">
              <div style="padding: 14px;">
                <span>{{ it.goodName }}</span>
                <div class="bottom clearfix">
                  <span style="color: red">价格：{{ it.selPrice }}  ￥</span>
                  <span style="color: red;margin-left: 10px">余量：{{ it.goodNum }}</span>
                </div>
              </div>
            </el-card>

          </el-col>
        </el-row>
      </div>
    </template>

    <el-dialog title="商品信息" :visible.sync="dialogFormVisible">
      <el-form :model="good">
        <el-form-item label="商品名称">
          {{ good.goodName }}
        </el-form-item>
        <el-form-item label="商品规格">
          {{ good.model }}
        </el-form-item>
        <el-form-item label="销售价格">
          {{ good.selPrice }}￥
        </el-form-item>
        <el-form-item label="商品图片">
          <img style="width: 400px; height: 100px; border: none; cursor: pointer" v-if="good.goodImg"
               :src="good.goodImg" class="avatar" alt="暂无"/>
        </el-form-item>
        <el-form-item label="商品描述">
          {{ good.goodDes }}
        </el-form-item>
        <el-form-item label="商品数量">
          {{ good.goodNum }}
        </el-form-item>
        <el-form-item label="商品品牌">
          {{ this.getBrandName(good.brdCode) }}
        </el-form-item>

        <el-form-item label="商品类别">
          {{ this.getGoodTypeName(good.typeCode) }}
        </el-form-item>
        <el-form-item label="商品供应商">
          {{ this.getSupplierName(good.supCode) }}
        </el-form-item>

        <el-form-item label="购买数量">
          <el-input-number v-model="good.sealNum" @change="handleChange" :min="0" :max="good.goodNum"
                           ></el-input-number>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false;good.sealNum=0">取 消</el-button>
        <el-button type="primary" @click="add(good)">加入购物车</el-button>
        <el-button type="primary" @click="seal(good)">立即下单</el-button>
      </div>
    </el-dialog>

<!--    购物车-->
    <el-dialog title="购物车" :visible.sync="sealsShowVi" width="60%">
      <el-form>
        <el-table
            highlight-current-row
            ref="multipleTable"
            :data="sealList"
            tooltip-effect="dark"
            style="width: 1000px"

            @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" ></el-table-column>
          <el-table-column type="index" width="100" label="序号" header-align="center" align="center"></el-table-column>
          <el-table-column prop="goodName" width="100" label="商品名称" header-align="center"
                           align="center"></el-table-column>
          <el-table-column prop="selPrice" width="140" label="销售价格" header-align="center"
                           align="center"></el-table-column>
          <el-table-column prop="goodImg" width="140" label="商品图片" header-align="center"
                           align="center">
            <template slot-scope="{ row }">
              <el-image style="width: auto; height: 50px; border: none; cursor: pointer" :src="row.goodImg"
                        alt=""></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="goodImg" width="240" label="数量" header-align="center"
                           align="center">
            <template slot-scope="{ row }">
              <el-input-number v-model="row.sealNum" @change="handleChange2" :min="0" :max="row.goodNum"
                               label="加入购物车"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-popconfirm title="确定删除吗？" width=40px @confirm="del(scope.row)">
                <el-button slot="reference" type="info" style="margin-left: 10px">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>

        </el-table>
        <span style="color: red;float: left">总计：{{total}}</span>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="sealList=[];reTotal()">清空购物车</el-button>
        <el-button @click="sealsShowVi = false;">关闭</el-button>
        <el-button type="primary" @click="seals()">对勾选商品结算</el-button>
      </div>
    </el-dialog>

    <br>
    <!--分页工具条-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :background="background"
        :current-page="currentPage"
        :page-sizes="[8, 16, 32, 64]"
        :page-size="8"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount">
    </el-pagination>


  </div>
</template>

<script>
import {buy} from "@/api/good";
import {deleteGood} from "@/api/good";
import {page} from "@/api/good";
import {getBrandList} from "@/api/brand"
import {getSupplierList} from "@/api/supplier"
import {getGoodTypeList} from "@/api/goodType"
import {forEach} from "core-js/stable/dom-collections";

export default {
  data() {
    return {
      sealsShowVi: false,//购物车
      background: true,
      // 每页显示的条数
      pageSize: 8,
      // 总记录数
      totalCount: 100,
      // 当前页码
      currentPage: 1,
      formLabelWidth: "120px",
      dialogFormVisible: false, //商品购买页面
      good: {//新增和编辑
        goodName: "",
        model: "",
        goodUnit: "",
        marPrice: "",
        selPrice: "",
        costPrice: "",
        goodImg: "",
        goodDes: "",
        goodCode: "",
        brdCode: "",
        typeCode: "",
        supCode: "",
        goodNum: "",
        sealNum: 0,
      },
      searchGood: {//条件查询
        goodName: "",
        model: "",
        goodUnit: "",
        marPrice: "",
        selPrice: "",
        costPrice: "",
        goodImg: "",
        goodDes: "",
        goodCode: "",
        brdCode: "",
        typeCode: "",
        supCode: "",
        goodNum: "",
        sealNum: 0,
      },
      tableData: [],
      brandList: [],
      goodTypeList: [],
      supplierList: [],
      sealList: [],
      // 复选框选中数据集合
      multipleSelection: [],
      total:0,//购物车价格总计
    };
  },

  methods: {
    del(obj){
      this.sealList.splice(this.sealList.findIndex(item => item === obj),1)
    },

    handleCardClick(it) {
      this.good = it
      this.dialogFormVisible = true
    },
    deleteById(id) {
      this.$confirm("此操作将删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteGood(id).then((res) => {
          if (res.data.code === 1) {
            this.$message.success("删除成功")
            this.page()
          }
        }).catch((e) => {
        })


      }).catch(() => {
        //用户点击取消按钮
        this.$message.info("已取消删除");
      });
    },

    selectById(id) {
      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].goodCode === id) {
          this.good = this.tableData[i];
          break;
        }
      }
      this.dialogForm2Visible = true

    },
    clearInfo() {
      this.good = {
        goodName: "",
        model: "",
        goodUnit: "",
        marPrice: "",
        selPrice: "",
        costPrice: "",
        goodImg: "",
        goodDes: "",
        goodCode: "",
        brdCode: "",
        typeCode: "",
        supCode: "",
        goodNum: "",
        sealNum: "",

      }
    },
    clearInfo2() {
      this.searchGood = {
        goodName: "",
        model: "",
        goodUnit: "",
        marPrice: "",
        selPrice: "",
        costPrice: "",
        goodImg: "",
        goodDes: "",
        goodCode: "",
        brdCode: "",
        typeCode: "",
        supCode: "",
        goodNum: "",
        sealNum: "",
      }
    },
    add(good) {
      if(this.sealList.findIndex(item => item === good)!=-1)
      {
        this.$message({
          message:"购物车中已存在该商品",
          type:"error"
        })
      }
      else
      {
        this.sealList.push(good)
        this.reTotal();
      }
      this.dialogFormVisible = false;
    },
    //分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val;
      this.page();
    },
    handleCurrentChange(val) {
      // 重新设置当前页码
      this.currentPage = val;
      this.page();
    },
    getBrandLists() {
      getBrandList().then((res) => {
        this.brandList = res.data.data;
      }).catch((e) => {
      })
    },
    //查询对应的品牌名
    getBrandName(code) {
      const brand = this.brandList.find(b => b.brdCode === code);
      return brand ? brand.brdName : '未知品牌';
    },

    getSupplierLists() {
      getSupplierList().then((res) => {
        this.supplierList = res.data.data;
      }).catch((e) => {
      })
    },
    //查询对应的供应商
    getSupplierName(code) {
      const supplier = this.supplierList.find(b => b.supCode === code);
      return supplier ? supplier.supName : '未知供应商';
    },

    getGoodTypeLists() {
      getGoodTypeList().then((res) => {
        this.goodTypeList = res.data.data;
      }).catch((e) => {
      })
    },
    //查询对应的类别
    getGoodTypeName(code) {
      const goodType = this.goodTypeList.find(b => b.typeCode === code);
      return goodType ? goodType.typeName : '未知类别';
    },

    // 购物车复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val;

    },


    // 查询分页数据
    page() {
      page(
          this.searchGood,
          this.currentPage,
          this.pageSize
      ).then((res) => {
        if (res.data.code != 0) {
          this.totalCount = res.data.data.total;
          this.tableData = res.data.data.rows;

        }
      }).catch((e) => {
      });
    },

    seal(good) {
      let total=good.sealNum*good.selPrice;
      this.$confirm("此操作将下单该商品" + good.sealNum + "个,总价为：<span style='color: red;'>" + total + "￥</span>, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true // 启用HTML解析
      }).then(() => {
      this.sealList.push(good);
      buy(this.sealList, total).then((res) => {
        this.sealList = [];
        this.dialogFormVisible = false;
        this.$message.success("下单成功")
        this.page()
      }).catch((e) => {
      })
      }).catch(() => {
        //用户点击取消按钮
        this.$message.info("已取消");
      });

    },

    seals(){
      let total=this.multipleSelection.reduce((accumulator, current) => {
        return accumulator + current.sealNum*current.selPrice;
      }, 0);
      this.$confirm("此操作将下单勾选商品,总价为：<span style='color: red;'>" + total + "￥</span>, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true // 启用HTML解析
      }).then(() => {

        buy(this.multipleSelection, total).then((res) => {
          this.multipleSelection.forEach(e=>this.del(e))
          this.multipleSelection = [];
          this.dialogFormVisible = false;
          this.$message.success("下单成功")
          this.page();
        }).catch((e) => {
        })
      }).catch(() => {
        //用户点击取消按钮
        this.$message.info("已取消");
      });


    },

    handleChange2(value) {
        this.reTotal();
    },
    handleChange(value) {
    },

    reTotal(){
      this.total=this.sealList.reduce((accumulator, current) => {
        return accumulator + current.sealNum*current.selPrice;
      }, 0);
    }

  },
  mounted() {
    this.page()
    this.getBrandLists()
    this.getSupplierLists()
    this.getGoodTypeLists()
  },



};
</script>


<style>
.image {
  width: 100%;
  height: 300px;
  display: block;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";

}

.clearfix:after {
  clear: both
}
</style>
